package com.laikan.reader.bookstore.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.activity.BookDesActivity;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;

public class ClassTwo extends BasicActivity {

    private static final String APP_CACAHE_DIRNAME = "/webcache";
    private WebView mWebView;
    private String url, title;
    private ImageView back_tv;
    private TextView title_tv;
    private RelativeLayout back_layout,common_loaddata_notice;
    private TextView common_prompt_content,common_refresh_net;
    private CircleProgressBar circleProgressBar;
    private long mLoadDelaynternalTime;
    Drawable drawable_back_tv;
    private TouchSwipeRefreshLayout mComment_SwipeRefresh;
    private boolean mIsLoadedSuccess;
    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            String[] bookUrl;
            if (url.contains("book")) {
                bookUrl = url.split("/");
                Intent intent = new Intent();
                intent.setClass(mContext, BookDesActivity.class);
                intent.putExtra("bookId", bookUrl[bookUrl.length - 1]);
                startActivity(intent);
            }else if (url.contains("more")) {
                Intent intent = new Intent();
                intent.setClass(mContext, CateRankActivity.class);
                intent.putExtra("mHtmlUrl", url);
                intent.putExtra("mode", "more");
                startActivity(intent);
            }else {
                view.loadUrl(url);
            }
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            mWebView.getSettings().setLoadsImagesAutomatically(true);
            dismissDialog();
            if(mIsLoadedSuccess){
                mComment_SwipeRefresh.setVisibility(View.VISIBLE);
                common_loaddata_notice.setVisibility(View.GONE);
                circleProgressBar.setVisibility(View.INVISIBLE);
            }else {
                mComment_SwipeRefresh.setVisibility(View.GONE);
                common_loaddata_notice.setVisibility(View.VISIBLE);
                circleProgressBar.setVisibility(View.INVISIBLE);
            }
        }

        public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
            mIsLoadedSuccess = true;
            if (circleProgressBar.getVisibility() == View.INVISIBLE) {
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            mIsLoadedSuccess = false;
            mWebView.loadUrl("");
//            mWebView.loadUrl("file:///android_asset/test.html");
            // super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };

    @Override
    protected void assignViews() {
        setContentView(R.layout.classtwo);
        title_tv = (TextView)findViewById(R.id.tv_title);
        mWebView = (WebView)findViewById(R.id.classifyWebview1);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        mComment_SwipeRefresh = (TouchSwipeRefreshLayout)findViewById(R.id.common_swiperefresh);
        mComment_SwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        url = getIntent().getStringExtra("mHtmlUrl");
        title = getIntent().getStringExtra("title");
        title_tv.setText(title);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);
        WebSettings webSetting = mWebView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        // 判断是否使用硬件加速
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
    }

    @Override
    protected void initData() {
        mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
        // 判断是否有网络，有的话，使用LOAD_DEFAULT，无网络时，使用LOAD_CACHE_ELSE_NETWORK。
        if (ActivityUitl.isNetworkAvailable(mContext)) {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 设置
        }
        // //
        // 缓存模式
        else {
            mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 设置 缓存模式
        }
        // 开启 DOM storage API 功能
        mWebView.getSettings().setDomStorageEnabled(true);
        // 开启 database storage API 功能
        mWebView.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
        // 设置数据库缓存路径
        mWebView.getSettings().setDatabasePath(cacheDirPath);
        // 设置 Application Caches 缓存目录
        mWebView.getSettings().setAppCachePath(cacheDirPath);
        // 开启 Application Caches 功能
        mWebView.getSettings().setAppCacheEnabled(true);
        // view.setBackgroundColor(0);
        // mWebView.setDrawingCacheEnabled(false);

        // 设置图片加载模式
        mWebView.getSettings().setBlockNetworkImage(false);
        // mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setUseWideViewPort(true);
        // 设置监听
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(webViewClient);
        mWebView.getSettings().setLoadsImagesAutomatically(false);
        if (ActivityUitl.isNetworkAvailable(ClassTwo.this)) {
            showDialog();
            mWebView.loadUrl(url);
        }else {
            mComment_SwipeRefresh.setVisibility(View.GONE);
            common_loaddata_notice.setVisibility(View.VISIBLE);
            common_prompt_content.setText(R.string.laikan_network_anomaly);
        }

        mComment_SwipeRefresh.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mComment_SwipeRefresh.setRefreshing(false);
                mWebView.loadUrl(url);

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        SPUtil.putBoolean("Single_click", false);
    }

    public void onBackPressed() {
        finish();
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.common_refresh_net:
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                circleProgressBar.setVisibility(View.VISIBLE);
                if(ActivityUitl.isNetworkAvailable(ClassTwo.this)){
                    mWebView.loadUrl(url);
                }else{
                    common_prompt_content.setText(R.string.laikan_network_anomaly);
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            default:
                break;
        }
    }
    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadDelaynternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    showLoadFailedView();
                }
            }, 1000);
        }else {
            showLoadFailedView();
        }
    }

    private void showLoadFailedView() {
        common_loaddata_notice.setVisibility(View.VISIBLE);
        circleProgressBar.setVisibility(View.INVISIBLE);
        common_refresh_net.setOnClickListener(ClassTwo.this);
    }
}
